import { BaseObserver } from './base.ts';

// 静态资源加载错误 | JS 代码运行错误、语法错误 | 异步错误 | 接口请求报错
export type errorType = 'resource' | 'js' | 'promise' | 'api';

export type reportData = {
    type: 'error';
    subType: errorType;
    msg?: string | Event;
    url?: string;
    lineNo?: number;
    columnNo?: number;
    stack?: string;
    html?: string;
    pageUrl: string;
    startTime: number
}

export class ErrorObserver extends BaseObserver {
    public handleUnhandledrejection() {
        window.addEventListener(
            'unhandledrejection',
            (e) => {
                const reportData = {
                    type: 'error',
                    subType: 'promise',
                    reason: e.reason?.stack,
                    pageUrl: window.location.href,
                    startTime: e.timeStamp,
                };
                this.lazyReportBatch(reportData);
            },
            true
        );
    }
    public handleResourceError() {
        window.addEventListener(
            'error',
            (e) => {
                // biome-ignore lint/suspicious/noExplicitAny: <explanation>
                const target = e.target as any;
                if (target.src || target.href) {
                    const url = target.src || target.href;
                    const reportData = {
                        type: 'error',
                        subType: 'resource',
                        url,
                        html: target.outerHTML,
                        pageUrl: window.location.href,
                        startTime: performance.now(),
                    };
                    this.lazyReportBatch(reportData);
                }
            },
            true
        );
    }
    public handleJsError() {
        window.onerror = (msg, url, lineNo, columnNo, error) => {
            const reportData = {
                type: 'error',
                subType: 'js',
                msg,
                url,
                lineNo,
                columnNo,
                stack: error?.stack,
                pageUrl: window.location.href,
                startTime: performance.now(),
            };
            this.lazyReportBatch(reportData);
        };
    } 
}
